<template>
  <div class="profile-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">个人中心</h1>
        <p class="page-subtitle">查看你的学习进度和统计数据</p>
      </div>
      
      <div class="header-right">
        <n-button 
          @click="showEditProfileModal = true"
        >
          <template #icon>
            <n-icon><Edit /></n-icon>
          </template>
          编辑资料
        </n-button>
      </div>
    </div>
    
    <!-- 用户信息卡片 -->
    <div class="profile-info">
      <n-card class="info-card">
        <div class="user-info">
          <div class="avatar-section">
            <n-avatar 
              :size="80"
              :src="authStore.user?.avatarUrl"
              :fallback-src="getDefaultAvatar()"
            >
              {{ getAvatarText() }}
            </n-avatar>
          </div>
          
          <div class="user-details">
            <h2 class="username">{{ authStore.user?.username }}</h2>
            <p class="email">{{ authStore.user?.email }}</p>
            <p class="join-date">
              <n-icon size="14"><Calendar /></n-icon>
              加入于 {{ authStore.user?.createdAt ? formatDate(authStore.user.createdAt, 'YYYY年MM月DD日') : '未知' }}
            </p>
          </div>
          
          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-number">{{ activityStats.totalActivities }}</div>
              <div class="stat-label">总活动</div>
            </div>
            
            <div class="stat-item">
              <div class="stat-number">{{ activityStats.streakDays }}</div>
              <div class="stat-label">连续天数</div>
            </div>
            
            <div class="stat-item">
              <div class="stat-number">{{ activityStats.streakDays }}</div>
              <div class="stat-label">最长连续</div>
            </div>
          </div>
        </div>
      </n-card>
    </div>
    
    <!-- 贡献图和统计 -->
    <div class="activity-section">
      <!-- 贡献图 -->
      <n-card title="学习活动" class="activity-card">
        <template #header-extra>
          <div class="activity-controls">
            <n-select
              v-model:value="selectedYear"
              :options="yearOptions"
              style="width: 100px"
              size="small"
            />
          </div>
        </template>
        
        <div class="heatmap-container">
          <!-- 加载状态 -->
          <div v-if="calendarStore.isLoading" class="loading-state">
            <n-spin size="large" />
          </div>
          
          <!-- 贡献图 -->
          <div v-else class="heatmap-wrapper">
            <div class="heatmap-legend">
              <span class="legend-text">少</span>
              <div class="legend-colors">
                <div class="legend-color" :style="{ backgroundColor: '#ebedf0' }"></div>
                <div class="legend-color" :style="{ backgroundColor: '#9be9a8' }"></div>
                <div class="legend-color" :style="{ backgroundColor: '#40c463' }"></div>
                <div class="legend-color" :style="{ backgroundColor: '#30a14e' }"></div>
                <div class="legend-color" :style="{ backgroundColor: '#216e39' }"></div>
              </div>
              <span class="legend-text">多</span>
            </div>
            
            <div class="heatmap-grid">
              <!-- 月份标签 -->
              <div class="month-labels">
                <div 
                  v-for="(month, index) in monthLabels" 
                  :key="index"
                  class="month-label"
                  :style="{ gridColumn: `${month.start} / ${month.end}` }"
                >
                  {{ month.name }}
                </div>
              </div>
              
              <!-- 星期标签 -->
              <div class="weekday-labels">
                <div class="weekday-label">一</div>
                <div class="weekday-label"></div>
                <div class="weekday-label">三</div>
                <div class="weekday-label"></div>
                <div class="weekday-label">五</div>
                <div class="weekday-label"></div>
                <div class="weekday-label">日</div>
              </div>
              
              <!-- 活动方块 -->
              <div class="activity-grid">
                <div 
                  v-for="day in heatmapData" 
                  :key="day.date"
                  class="activity-day"
                  :class="getActivityLevel(day.count)"
                  :title="getActivityTooltip(day)"
                  @click="selectDate(day.date)"
                >
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 活动摘要 -->
        <div class="activity-summary">
          <div class="summary-item">
            <span class="summary-label">今年总计:</span>
            <span class="summary-value">{{ yearlyTotal }} 次活动</span>
          </div>
          
          <div class="summary-item">
            <span class="summary-label">最活跃:</span>
            <span class="summary-value">{{ mostActiveDay }}</span>
          </div>
        </div>
      </n-card>
      
      <!-- 最近活动 -->
      <n-card title="最近活动" class="recent-activity-card">
        <div class="recent-activities">
          <!-- 加载状态 -->
          <div v-if="calendarStore.isLoading" class="loading-state">
            <n-spin size="small" />
          </div>
          
          <!-- 活动列表 -->
          <div v-else-if="recentActivities.length > 0" class="activities-list">
            <div 
              v-for="activity in recentActivities" 
              :key="activity.id"
              class="activity-item"
            >
              <div class="activity-icon">
                <n-icon :color="getActivityTypeColor(activity.type)">
                  <component :is="getActivityTypeIcon(activity.type)" />
                </n-icon>
              </div>
              
              <div class="activity-content">
                <div class="activity-title">{{ activity.description }}</div>
                <div class="activity-time">
                  {{ formatRelativeTime(activity.date) }}
                </div>
              </div>
            </div>
          </div>
          
          <!-- 空状态 -->
          <div v-else class="empty-activities">
            <n-icon size="48" color="#d1d5db">
              <Activity />
            </n-icon>
            <p>暂无最近活动</p>
          </div>
        </div>
      </n-card>
    </div>
    
    <!-- 学习统计 -->
    <div class="stats-section">
      <div class="stats-grid">
        <!-- 算法题统计 -->
        <n-card title="算法题库" class="stat-card">
          <div class="stat-content">
            <div class="stat-main">
              <div class="stat-number large">{{ algorithmStats.total }}</div>
              <div class="stat-label">总题数</div>
            </div>
            
            <div class="stat-breakdown">
              <div class="breakdown-item">
                <div class="breakdown-dot easy"></div>
                <span>简单: {{ algorithmStats.easy }}</span>
              </div>
              <div class="breakdown-item">
                <div class="breakdown-dot medium"></div>
                <span>中等: {{ algorithmStats.medium }}</span>
              </div>
              <div class="breakdown-item">
                <div class="breakdown-dot hard"></div>
                <span>困难: {{ algorithmStats.hard }}</span>
              </div>
            </div>
          </div>
        </n-card>
        
        <!-- 待办事项统计 -->
        <n-card title="待办事项" class="stat-card">
          <div class="stat-content">
            <div class="stat-main">
              <div class="stat-number large">{{ todoStats.completed }}</div>
              <div class="stat-label">已完成</div>
            </div>
            
            <div class="stat-breakdown">
              <div class="breakdown-item">
                <div class="breakdown-dot pending"></div>
                <span>待办: {{ todoStats.pending }}</span>
              </div>
              <div class="breakdown-item">
                <div class="breakdown-dot overdue"></div>
                <span>逾期: {{ todoStats.overdue }}</span>
              </div>
            </div>
          </div>
        </n-card>
        
        <!-- 日历事件统计 -->
        <n-card title="日历事件" class="stat-card">
          <div class="stat-content">
            <div class="stat-main">
              <div class="stat-number large">{{ calendarStats.thisMonth }}</div>
              <div class="stat-label">本月事件</div>
            </div>
            
            <div class="stat-breakdown">
              <div class="breakdown-item">
                <div class="breakdown-dot upcoming"></div>
                <span>即将到来: {{ calendarStats.upcoming }}</span>
              </div>
            </div>
          </div>
        </n-card>
      </div>
    </div>
    
    <!-- 编辑资料模态框 -->
    <n-modal 
      v-model:show="showEditProfileModal" 
      preset="card" 
      title="编辑资料" 
      style="width: 500px"
    >
      <n-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-placement="top"
      >
        <n-form-item path="username" label="用户名">
          <n-input 
            v-model:value="profileForm.username" 
            placeholder="请输入用户名"
          />
        </n-form-item>
        
        <n-form-item path="email" label="邮箱">
          <n-input 
            v-model:value="profileForm.email" 
            placeholder="请输入邮箱"
            disabled
          />
        </n-form-item>
        
        <n-form-item path="avatar_url" label="头像URL">
          <n-input 
            v-model:value="profileForm.avatar_url" 
            placeholder="请输入头像URL（可选）"
          />
        </n-form-item>
      </n-form>
      
      <template #footer>
        <div class="modal-footer">
          <n-button @click="showEditProfileModal = false">取消</n-button>
          <n-button 
            type="primary" 
            :loading="authStore.isLoading"
            @click="handleUpdateProfile"
          >
            保存
          </n-button>
        </div>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  NButton,
  NIcon,
  NCard,
  NAvatar,
  NSelect,
  NSpin,
  NModal,
  NForm,
  NFormItem,
  NInput,
  useMessage,
  type FormInst,
  type FormRules
} from 'naive-ui'
import {
  Edit,
  Calendar,
  Activity,
  Code,
  CircleCheck,
  CalendarEvent,
  // Star,
  // Clock
} from '@vicons/tabler'
import { useAuthStore } from '@/stores/auth'
import { useAlgorithmsStore } from '@/stores/algorithms'
import { useTodosStore } from '@/stores/todos'
import { useCalendarStore } from '@/stores/calendar'
import { 
  formatDate, 
  formatRelativeTime,
  isValidEmail
} from '@/utils'
// import type { UpdateProfileRequest } from '@/types/auth'

const message = useMessage()
const authStore = useAuthStore()
const algorithmsStore = useAlgorithmsStore()
const todosStore = useTodosStore()
const calendarStore = useCalendarStore()

// 表单引用
const profileFormRef = ref<FormInst | null>(null)

// 模态框状态
const showEditProfileModal = ref(false)

// 选中的年份
const selectedYear = ref(new Date().getFullYear())

// 表单数据
const profileForm = ref({
  username: '',
  email: '',
  avatar_url: ''
})

// 年份选项
const yearOptions = computed(() => {
  const currentYear = new Date().getFullYear()
  const years = []
  for (let i = currentYear; i >= currentYear - 5; i--) {
    years.push({ label: `${i}年`, value: i })
  }
  return years
})

// 活动统计
const activityStats = computed(() => calendarStore.activityStats)
const recentActivities = computed(() => calendarStore.recentActivities)

// 热力图数据
const heatmapData = computed(() => {
  const year = selectedYear.value
  const startDate = new Date(year, 0, 1)
  const endDate = new Date(year, 11, 31)
  const days = []
  
  // 获取年初第一个周一
  const firstMonday = new Date(startDate)
  const dayOfWeek = firstMonday.getDay()
  const daysToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1
  firstMonday.setDate(firstMonday.getDate() - daysToMonday)
  
  // 生成一年的数据
  const current = new Date(firstMonday)
  while (current <= endDate || days.length % 7 !== 0) {
    const dateStr = current.toISOString().split('T')[0]
    const activity = calendarStore.activities.find((a: any) => a.date === dateStr)
    
    days.push({
      date: dateStr,
      count: activity?.count || 0,
      isCurrentYear: current.getFullYear() === year
    })
    
    current.setDate(current.getDate() + 1)
  }
  
  return days
})

// 月份标签
const monthLabels = computed(() => {
  const months = [
    '1月', '2月', '3月', '4月', '5月', '6月',
    '7月', '8月', '9月', '10月', '11月', '12月'
  ]
  
  const labels = []
  const weeksInYear = Math.ceil(heatmapData.value.length / 7)
  
  for (let i = 0; i < 12; i++) {
    const monthStart = Math.floor((i * weeksInYear) / 12) + 1
    const monthEnd = Math.floor(((i + 1) * weeksInYear) / 12) + 1
    
    if (monthEnd > monthStart) {
      labels.push({
        name: months[i],
        start: monthStart,
        end: monthEnd
      })
    }
  }
  
  return labels
})

// 年度总计
const yearlyTotal = computed(() => {
  return heatmapData.value
    .filter(day => day.isCurrentYear)
    .reduce((sum, day) => sum + day.count, 0)
})

// 最活跃的一天
const mostActiveDay = computed(() => {
  const maxActivity = heatmapData.value
    .filter(day => day.isCurrentYear)
    .reduce((max, day) => day.count > max.count ? day : max, { count: 0, date: '' })
  
  if (maxActivity.count === 0) return '暂无'
  
  return `${formatDate(maxActivity.date, 'MM月DD日')} (${maxActivity.count}次)`
})

// 算法题统计
const algorithmStats = computed(() => {
  const algorithms = algorithmsStore.problems
  return {
    total: algorithms.length,
    easy: algorithms.filter((a: any) => a.difficulty === 'easy').length,
    medium: algorithms.filter((a: any) => a.difficulty === 'medium').length,
    hard: algorithms.filter((a: any) => a.difficulty === 'hard').length
  }
})

// 待办事项统计
const todoStats = computed(() => {
  const todos = todosStore.todos
  const now = new Date()
  
  return {
    completed: todos.filter((t: any) => t.completed).length,
    pending: todos.filter((t: any) => !t.completed).length,
    overdue: todos.filter((t: any) => 
      !t.completed && 
      t.dueDate &&
        new Date(t.dueDate) < now
    ).length
  }
})

// 日历事件统计
const calendarStats = computed(() => {
  const events = calendarStore.events
  const now = new Date()
  const thisMonth = now.getMonth()
  const thisYear = now.getFullYear()
  
  return {
    thisMonth: events.filter((e: any) => {
      const eventDate = new Date(e.date)
      return eventDate.getMonth() === thisMonth && eventDate.getFullYear() === thisYear
    }).length,
    upcoming: events.filter((e: any) => new Date(e.date) > now).length
  }
})

// 表单验证规则
const profileRules: FormRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: ['input', 'blur']
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: ['input', 'blur']
    },
    {
      validator: (_rule, value) => isValidEmail(value),
      message: '请输入有效的邮箱地址',
      trigger: ['input', 'blur']
    }
  ]
}

// 获取默认头像
const getDefaultAvatar = () => {
  return `https://api.dicebear.com/7.x/initials/svg?seed=${authStore.user?.username}`
}

// 获取头像文字
const getAvatarText = () => {
  return authStore.user?.username?.charAt(0).toUpperCase() || 'U'
}

// 获取活动等级
const getActivityLevel = (count: number) => {
  if (count === 0) return 'level-0'
  if (count <= 2) return 'level-1'
  if (count <= 4) return 'level-2'
  if (count <= 6) return 'level-3'
  return 'level-4'
}

// 获取活动提示
const getActivityTooltip = (day: any) => {
  const date = formatDate(day.date, 'YYYY年MM月DD日')
  if (day.count === 0) {
    return `${date}: 无活动`
  }
  return `${date}: ${day.count} 次活动`
}

// 获取活动类型图标
const getActivityTypeIcon = (type: string) => {
  const icons: Record<string, any> = {
    login: Activity,
    task_created: CircleCheck,
    task_completed: CircleCheck,
    algorithm_created: Code,
    code_saved: Code,
    event_created: CalendarEvent
  }
  return icons[type] || Activity
}

// 获取活动类型颜色
const getActivityTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    login: '#3b82f6',
    task_created: '#10b981',
    task_completed: '#059669',
    algorithm_created: '#8b5cf6',
    code_saved: '#6366f1',
    event_created: '#f59e0b'
  }
  return colors[type] || '#6b7280'
}

// 选择日期
const selectDate = (date: string) => {
  // 可以在这里添加日期选择的逻辑
  console.log('Selected date:', date)
}

// 更新用户资料
const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    await profileFormRef.value.validate()
    
    const updateData = {
      username: profileForm.value.username,
      avatar_url: profileForm.value.avatar_url || undefined
    }
    
    await authStore.updateProfile(updateData)
    
    showEditProfileModal.value = false
    message.success('资料更新成功')
  } catch (error) {
    console.error('Update profile failed:', error)
  }
}

// 初始化数据
const initData = async () => {
  try {
    // 获取活动数据
    await calendarStore.fetchActivityHeatmap(selectedYear.value)
    await calendarStore.fetchRecentActivities()
    await calendarStore.fetchActivityStats()
    
    // 获取其他数据
    await algorithmsStore.fetchProblems()
    await todosStore.fetchTodos()
    await calendarStore.fetchEvents()
  } catch (error) {
    console.error('Failed to load profile data:', error)
  }
}

// 监听用户信息变化
const updateProfileForm = () => {
  if (authStore.user) {
    profileForm.value = {
      username: authStore.user.username,
      email: authStore.user.email,
      avatar_url: authStore.user.avatarUrl || ''
    }
  }
}

// 组件挂载
onMounted(() => {
  initData()
  updateProfileForm()
})
</script>

<style scoped>
.profile-page {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 4px 0;
}

.page-subtitle {
  color: #6b7280;
  margin: 0;
}

.profile-info {
  margin-bottom: 24px;
}

.info-card {
  border-radius: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 24px;
}

.avatar-section {
  flex-shrink: 0;
}

.user-details {
  flex: 1;
}

.username {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 4px 0;
}

.email {
  color: #6b7280;
  margin: 0 0 8px 0;
}

.join-date {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #6b7280;
  font-size: 14px;
  margin: 0;
}

.user-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.stat-number.large {
  font-size: 32px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-top: 4px;
}

.activity-section {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 24px;
  margin-bottom: 24px;
}

.activity-card,
.recent-activity-card {
  border-radius: 12px;
}

.activity-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.heatmap-container {
  margin-bottom: 16px;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.heatmap-wrapper {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.heatmap-legend {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
  font-size: 12px;
  color: #6b7280;
}

.legend-colors {
  display: flex;
  gap: 2px;
}

.legend-color {
  width: 10px;
  height: 10px;
  border-radius: 2px;
}

.legend-text {
  font-size: 11px;
}

.heatmap-grid {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: 8px;
}

.month-labels {
  grid-column: 2;
  display: grid;
  grid-template-columns: repeat(53, 1fr);
  gap: 2px;
  margin-bottom: 4px;
}

.month-label {
  font-size: 11px;
  color: #6b7280;
  text-align: center;
}

.weekday-labels {
  display: flex;
  flex-direction: column;
  gap: 2px;
  padding-top: 20px;
}

.weekday-label {
  height: 10px;
  font-size: 9px;
  color: #6b7280;
  display: flex;
  align-items: center;
}

.activity-grid {
  display: grid;
  grid-template-columns: repeat(53, 1fr);
  grid-template-rows: repeat(7, 1fr);
  gap: 2px;
  grid-auto-flow: column;
}

.activity-day {
  width: 10px;
  height: 10px;
  border-radius: 2px;
  cursor: pointer;
  transition: all 0.2s;
}

.activity-day:hover {
  transform: scale(1.2);
}

.activity-day.level-0 {
  background-color: #ebedf0;
}

.activity-day.level-1 {
  background-color: #9be9a8;
}

.activity-day.level-2 {
  background-color: #40c463;
}

.activity-day.level-3 {
  background-color: #30a14e;
}

.activity-day.level-4 {
  background-color: #216e39;
}

.activity-summary {
  display: flex;
  gap: 24px;
  font-size: 14px;
}

.summary-item {
  display: flex;
  gap: 8px;
}

.summary-label {
  color: #6b7280;
}

.summary-value {
  font-weight: 500;
  color: #1f2937;
}

.recent-activities {
  max-height: 400px;
  overflow-y: auto;
}

.activities-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.activity-item:hover {
  background-color: #f9fafb;
}

.activity-icon {
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 2px;
}

.activity-time {
  font-size: 12px;
  color: #6b7280;
}

.empty-activities {
  text-align: center;
  padding: 48px 24px;
  color: #6b7280;
}

.empty-activities p {
  margin: 12px 0 0 0;
}

.stats-section {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

.stat-card {
  border-radius: 12px;
}

.stat-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.stat-main {
  text-align: center;
}

.stat-breakdown {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.breakdown-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #6b7280;
}

.breakdown-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.breakdown-dot.easy {
  background-color: #10b981;
}

.breakdown-dot.medium {
  background-color: #f59e0b;
}

.breakdown-dot.hard {
  background-color: #ef4444;
}

.breakdown-dot.pending {
  background-color: #6b7280;
}

.breakdown-dot.overdue {
  background-color: #ef4444;
}

.breakdown-dot.upcoming {
  background-color: #3b82f6;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .activity-section {
    grid-template-columns: 1fr;
  }
  
  .recent-activity-card {
    order: -1;
  }
}

@media (max-width: 768px) {
  .profile-page {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .user-info {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .user-stats {
    justify-content: center;
    gap: 24px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .heatmap-grid {
    grid-template-columns: 1fr;
  }
  
  .weekday-labels {
    display: none;
  }
  
  .activity-grid {
    grid-template-columns: repeat(26, 1fr);
  }
}
</style>